var service = require('./utilService.js')
var noti = require('./WxNotificationCenter.js')

var favIds = []
var favDict = {}

function configProductList(list) {

  for (var index in list) {
    var id = list[index].id != null ? list[index].id : list[index].goodsId 

    if (favIds.indexOf(id) != -1) { //存在
      var store = favDict[id]
      if (store == 0) { //取消收藏
        if (list[index].store == 1) {
          list[index].store = 0
          var count = list[index].favorityCount - 1
          list[index].favorityCount = count < 0 ? 0 : count
        }
      } else { //添加收藏
        if (list[index].store == 0) { //没有收藏
          list[index].favorityCount += 1
          list[index].store = 1
        }
      }
    }
  }

  return list
}

function configFavs(id, add) {

  if (favIds.indexOf(id) == -1) {
    favIds.push(id)
  }

  favDict[id] = add == true ? 1 : 0

  postNoti()
}

function postNoti() {
  noti.postNotificationName(noti.refreshProdutsNotiName)
}

function favRequest(id, callback) {
  var that = this
  wx.showLoading({
    title: '请稍等',
  })
  service.favRequest(id, 0,
    function (data) {
      wx.hideLoading()
      wx.showToast({
        title: '已收藏',
        icon: 'success',
        duration: 2000
      })
      configFavs(id, 1)
      typeof callback == "function" && callback(data)
    },
    function (error) {
      var msg = error.message != null ? error.message : error.errMsg
      wx.hideLoading()
      wx.showToast({
        title: msg,
        icon: 'none',
        duration: 2000
      })
    })
}

function deleteFavRequest(id, callback) {
  var that = this
  wx.showLoading({
    title: '请稍等',
  })
  service.deleteFavRequest(id,
    function (data) {
      wx.hideLoading()
      wx.showToast({
        title: '已取消',
        icon: 'success',
        duration: 2000
      })
      configFavs(id, 0)
      typeof callback == "function" && callback(data)
    },
    function (error) {
      wx.hideLoading()
      wx.showToast({
        title: error.message,
        icon: 'none',
        duration: 2000
      })
    })
}

module.exports = {
  configProductList: configProductList,
  favRequest: favRequest,
  deleteFavRequest: deleteFavRequest
}
